// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  
  try {
    // 获取用户信息
    const userInfo = await db.collection('users').where({
      _openid: wxContext.OPENID
    }).get()
    
    if (userInfo.data.length === 0) {
      // 新用户，创建用户记录
      const newUser = {
        _openid: wxContext.OPENID,
        nickName: event.nickName || '匿名用户',
        avatarUrl: event.avatarUrl || '',
        createTime: db.serverDate(),
        lastLoginTime: db.serverDate(),
        gameCount: 0,
        winCount: 0
      }
      
      const result = await db.collection('users').add({
        data: newUser
      })
      
      return {
        success: true,
        isNewUser: true,
        userInfo: newUser
      }
    } else {
      // 更新老用户登录时间
      await db.collection('users').where({
        _openid: wxContext.OPENID
      }).update({
        data: {
          lastLoginTime: db.serverDate()
        }
      })
      
      return {
        success: true,
        isNewUser: false,
        userInfo: userInfo.data[0]
      }
    }
  } catch (error) {
    console.error('登录失败:', error)
    return {
      success: false,
      error: error.message
    }
  }
} 